/*
 * VolleyUtils.java
 * classes : ruint.core.utils.volley.VolleyUtils
 * @author ruint
 * V 1.0.0
 * Create at 2014-11-12 上午11:18:38
 */
package com.ruint.core.utils.volley;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.http.entity.mime.content.ByteArrayBody;

import android.content.Context;

import com.android.volley.RequestQueue;
import com.android.volley.RequestQueue.RequestFilter;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.ruint.core.reflect.ReflectUtil;
import com.ruint.core.utils.bitmap.ResizeUtils;
import com.ruint.core.utils.preferences.CorePreferences;
import com.ruint.core.utils.ui.ToastUtils;
import com.ruint.core.view.dialog.CustomProgressDialog;
import com.ruint.core.view.supertoasts.SuperToast.Animations;

/**
 * ruint.core.utils.volley.VolleyUtils
 * 
 * @author ruint <br/>
 *         create at 2014-11-12 上午11:18:38
 */
public class RequestManager {

  private static RequestManager mInstance;
  private static RequestQueue mRequestQueue;

  public static RequestManager getInstance() {
    if (mInstance == null) {
      mInstance = new RequestManager();
    }
    return mInstance;
  }

  public interface GenericCallback<T> {
    void onResponse(T result);

    void onRequestFailed();
  }

  public static void init() {
    mRequestQueue = RequestCore.getRequestQueue();
  }

  public <T> void get(final Context context, final T t, String url, final GenericCallback<T> callback) {
    final CustomProgressDialog dialog = new CustomProgressDialog(context);
    dialog.show();
    OmniRequest request = new OmniRequest(url, new Listener<String>() {

      @SuppressWarnings("unchecked")
      @Override
      public void onResponse(String response) {
        if (ReflectUtil.isListType(t.getClass())) {
          callback.onResponse((T) ReflectUtil.getList(response, t));
        } else {
          callback.onResponse(ReflectUtil.getObject(response, t));
        }
        if (dialog.isShowing()) {
          dialog.dismiss();
        }
      }
    }, new ErrorListener() {

      @Override
      public void onErrorResponse(VolleyError error) {
        if (error != null) {
          if (error.networkResponse != null)
            CorePreferences.DEBUG("VolleyError  : " + new String(error.networkResponse.data));
        }
        callback.onRequestFailed();
        if (dialog.isShowing()) {
          dialog.dismiss();
        }
        ToastUtils.showCustomToast(context, "数据请求失败", Animations.FLYIN);
      }
    });
    mRequestQueue.add(request);
  }

  public <T> void post(final Context context, final T t, String url, final Map<String, String> params,
      final Map<String, File> files, final boolean isCompress, final GenericCallback<T> callback) {
    final CustomProgressDialog dialog = new CustomProgressDialog(context);
    dialog.show();
    MultipartStringRequest request = new MultipartStringRequest(url, new Listener<String>() {

      @SuppressWarnings("unchecked")
      @Override
      public void onResponse(String response) {
        if (ReflectUtil.isListType(t.getClass())) {
          callback.onResponse((T) ReflectUtil.getList(response, t));
        } else {
          callback.onResponse(ReflectUtil.getObject(response, t));
        }
        if (dialog.isShowing()) {
          dialog.dismiss();
        }
      }
    }, new ErrorListener() {

      @Override
      public void onErrorResponse(VolleyError error) {
        if (error != null) {
          if (error.networkResponse != null)
            CorePreferences.DEBUG("VolleyError  : " + new String(error.networkResponse.data));
          callback.onRequestFailed();
          ToastUtils.showCustomToast(context, "数据请求失败", Animations.FLYIN);
        }
        if (dialog.isShowing()) {
          dialog.dismiss();
        }
      }
    }) {

      @Override
      public Map<String, File> getFile() {
        if (!isCompress) {
          return files;
        }
        return super.getFile();
      }

      @Override
      public Map<String, String> getString() {
        return params;
      }

      @Override
      public Map<String, ByteArrayBody> getByte() {
        if (isCompress) {
          Iterator<Entry<String, File>> iterator = files.entrySet().iterator();
          while (iterator.hasNext()) {
            Map.Entry<String, File> entry = iterator.next();
            String key = entry.getKey();
            File file = entry.getValue();
            CorePreferences.DEBUG(key + "\n" + file.getAbsolutePath() + "\n" + file.length());
            try {
              super.getByte().put(key, new ByteArrayBody(ResizeUtils.revitionBitmap(file), key));
            } catch (IOException e) {
              CorePreferences.DEBUG(key + " : " + "revition failed" + e.getMessage());
            }
          }
        }
        return super.getByte();
      }
    };
    mRequestQueue.add(request);
  }

  public void cancelAll(RequestFilter filter) {
    mRequestQueue.cancelAll(filter);
  }

  public void cancelAll(final Object tag) {
    mRequestQueue.cancelAll(tag);
  }
}
